import { defineStore }      from 'pinia';
import { useTemplateStore } from 'stores/templateStore';
import { Mapper, Project }  from 'src/types';
import { showColumns, showTables } from 'src/api/DatabaseApi';
import { Table } from 'src/models/Orm';
import { notion, pathJoin } from 'src/api/SysApi';
import { renderTemplateContent } from 'src/api/render';
import { saveFile } from 'src/api/FileApi';
import { EmptyObject } from 'stores/index';
import { useProjectStore } from 'stores/projectStore';
import { Notify } from 'quasar';

export const useGenStore = defineStore('gen', () => {
  const underscoreToCamelCase = (str: string) => {
    return str.replace(/_([a-z])/g, function (match, letter) {
      return letter.toUpperCase();
    });
  };
  const capitalizeFirstLetter = (str: string) => {
    return str.charAt(0).toUpperCase() + str.slice(1);
  };

  async function getTablesData() {
    const project = (await useProjectStore().project) as Project;
    const tables = project.out?.tables as string[];
    console.log(tables);
    const tablesObject = {};
    tables.forEach((i) => {
      tablesObject[i] = { table: {}, columns: [] };
    });
    ((await showColumns(tables)).results as Table[]).forEach((i) => {
      tablesObject[i.TABLE_NAME].columns.push({
        ...i,
        COLUMN_NAME_HUMP: underscoreToCamelCase(i.COLUMN_NAME),
        COLUMN_NAME_INITIALS_HUMP: capitalizeFirstLetter(
          underscoreToCamelCase(i.COLUMN_NAME)
        ),
      });
    });
    ((await showTables()).results as Table[]).forEach((i) => {
      if (tables.includes(i.TABLE_NAME))
        tablesObject[i.TABLE_NAME].table = {
          ...i,
          TABLE_NAME_HUMP: underscoreToCamelCase(i.TABLE_NAME),
          TABLE_NAME_INITIALS_HUMP: capitalizeFirstLetter(
            underscoreToCamelCase(i.TABLE_NAME)
          ),
        };
    });
    return tablesObject;
  }

  async function gen() {
    const project = await useProjectStore().project;
    const tables = project.out?.tables as string[];
    const tablesObject: EmptyObject = {};
    tables.forEach((i) => {
      tablesObject[i] = { table: {}, columns: [] };
    });
    ((await showColumns(tables)).results as Table[]).forEach((i) => {
      tablesObject[i.TABLE_NAME].columns.push({
        ...i,
        COLUMN_NAME_HUMP: underscoreToCamelCase(i.COLUMN_NAME),
        COLUMN_NAME_INITIALS_HUMP: capitalizeFirstLetter(
          underscoreToCamelCase(i.COLUMN_NAME)
        ),
      });
    });
    ((await showTables()).results as Table[]).forEach((i) => {
      if (tables.includes(i.TABLE_NAME))
        tablesObject[i.TABLE_NAME].table = {
          ...i,
          TABLE_NAME_HUMP: underscoreToCamelCase(i.TABLE_NAME),
          TABLE_NAME_INITIALS_HUMP: capitalizeFirstLetter(
            underscoreToCamelCase(i.TABLE_NAME)
          ),
        };
    });
    //开始生成表
    for (const i of Object.keys(tablesObject)) {
      const data = {
        ...tablesObject[i],
        ...new Function(
          'return' +
            (
              await useTemplateStore().getTemplateContentById(
                project.out?.define
              )
            ).content
        )(),
      };
      for (const j of project?.mapper as Mapper[]) {
        const renderText = await renderTemplateContent(
          (
            await useTemplateStore().getTemplateContentById(j.templateId)
          ).content,
          data
        );
        const outPath = pathJoin(
          project.out?.path as string,
          ...(project.out?.parent.split('.') as string[]),
          ...(j.generatedPath?.split('.') as string[]),
          data.table.TABLE_NAME_INITIALS_HUMP +
            `${
              j.postfix
                ? capitalizeFirstLetter(j.data.componentName as string)
                : ''
            }` +
            '.' +
            j.data.lang
        );
        await saveFile(outPath, renderText);
      }
    }
    Notify.create({
      message: '代码生成成功',
      position: 'bottom',
      classes:'bg-red-love text-bold dyh text-body2',
      timeout: 2000,
    })
    notion(
      '代码生成成功 -> 查看目录',
      `生成表：${tables.join(',')}`,
      project.out?.path as string
    );
  }

  return {
    gen,
    underscoreToCamelCase,
    capitalizeFirstLetter,
    getTablesData,
  };
});
